package kr.hkit.powerjava.chapter26.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import kr.hkit.powerjava.chapter26.DbProperties;

public class ConnectionFactory {
	private String driver;
	private String url;
	private String user;
	private String password;
	
	private static ConnectionFactory instance = new ConnectionFactory();
	
	private ConnectionFactory(){
		loadProperties();
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			System.err.printf("%s", "MySQL Driver not found");
			System.exit(-1);
		}
	}
	
	public static Connection getConnection(){
		return instance.createConnection();
	}
	
	private Connection createConnection(){
		Connection con = null;
		try {
			con = DriverManager.getConnection(url, user, password);
			System.out.println("MySQL Connection Success");
		} catch (SQLException e) {
			System.out.printf("%s", "ERROR : Unable Connect to MySQL");
		}
		return con;
	}
	
	private void loadProperties(){
		Properties prop = DbProperties.loadPropertis("dbcon.xml");
		driver = prop.getProperty("DRIVER");
		url = prop.getProperty("URL");
		user = prop.getProperty("USER");
		password = prop.getProperty("PASSWORD");
	}
}
